//
//  MessageController.m
//  DianDangDai
//
//  Created by bhf on 2017/12/22.
//  Copyright © 2017年 bhf. All rights reserved.
//

#import "MessageController.h"
#import "MessageCell.h"
#import "MessageModel.h"
@interface MessageController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger page;
@end

@implementation MessageController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    self.navigationController.navigationBar.translucent = NO;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"站内信";
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    _page = 1;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestData)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    // Do any additional setup after loading the view.
}

- (void)requestData {
    _page = 1;
    _dataArray = [NSMutableArray array];
    NSDictionary *userInformation = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"userInformation"];
    NSString *sign = userInformation[@"sign"];
    NSString *urlString = [NSString stringWithFormat:@"%@OPT=1020&currPage=1&pageSize=10&sign=%@",API_LOGIN_URL_STRING,sign];
    NSLog(@"%@",urlString);
    [[CDHttpHelper defaultCDHttpHelper] get:urlString params:nil success:^(id responseObj) {
        NSDictionary *dict = [responseObj objectFromJSONData];
        NSLog(@"%@",dict);
        [self.view makeToast:dict[@"msg"]];
        for (NSDictionary *dic in dict[@"message"]) {
            MessageModel *model = [MessageModel mj_objectWithKeyValues:dic];
            NSLog(@"%@",model.read_status);
            [self.dataArray addObject:model];
        }
        if (_dataArray.count<10) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.tableView.mj_footer resetNoMoreData];
        }
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
    } showHUD:NO];
}

- (void)loadMoreData {
    _page++;
    NSDictionary *userInformation = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"userInformation"];
    NSString *sign = userInformation[@"sign"];
    NSString *urlString = [NSString stringWithFormat:@"%@OPT=1020&currPage=%ld&pageSize=10&sign=%@",API_LOGIN_URL_STRING,(long)_page,sign];
    NSLog(@"%@",urlString);
    [[CDHttpHelper defaultCDHttpHelper] get:urlString params:nil success:^(id responseObj) {
        NSDictionary *dict = [responseObj objectFromJSONData];
        NSLog(@"%@",dict);
        [self.view makeToast:dict[@"msg"]];
        for (NSDictionary *dic in dict[@"message"]) {
            MessageModel *model = [MessageModel mj_objectWithKeyValues:dic];
            NSLog(@"%@",model.read_status);
            [self.dataArray addObject:model];
        }
        [self.tableView.mj_footer endRefreshing];
        
        if (_dataArray.count%10 != 0) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.tableView.mj_footer resetNoMoreData];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
    } showHUD:NO];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"msg_cell" forIndexPath:indexPath];
    MessageModel *model = self.dataArray[indexPath.row];
    cell.content.text = model.content;
    cell.time.text = model.time;
    if ([model.read_status isEqualToString:@"未读"]) {
        cell.already.textColor = [UIColor redColor];
        cell.already.text = model.read_status;
    } else {
        cell.already.textColor = [UIColor colorWithHex:@"#333333"];
        cell.already.text = model.read_status;
    }
    
    cell.title.text = model.title;
    // Configure the cell...
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 111;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageModel *model = self.dataArray[indexPath.row];
    NSDictionary *userInformation = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"userInformation"];
    NSString *sign = userInformation[@"sign"];
    NSString *urlString = [NSString stringWithFormat:@"%@OPT=1035&msgId=%ld&sign=%@",API_LOGIN_URL_STRING,model.id,sign];
    NSLog(@"%@",urlString);
    //查看详情
    [[CDHttpHelper defaultCDHttpHelper] get:urlString params:nil success:^(id responseObj) {
        NSDictionary *dict = [responseObj objectFromJSONData];
        NSLog(@"%@",dict);
        NSInteger code = [dict[@"code"] integerValue];
        if (code == 0) {
            ZCAlertViewController *alert = [ZCAlertViewController alertControllerWithTitle:model.title message:model.content];
            [alert setMessageAlignment:NSTextAlignmentLeft];
            ZCAlertAction *action = [ZCAlertAction actionWithTitle:@"返回" handler:^(ZCAlertAction *action) {
                MessageCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                if ([cell.already.text isEqualToString:@"未读"]) {
                    cell.already.text = @"已读";
                    cell.already.textColor = [UIColor colorWithHex:@"#333333"];
                }
                
            }];
            //根据id删除删除该条
            ZCAlertAction *action2 = [ZCAlertAction actionWithTitle:@"删除" handler:^(ZCAlertAction *action) {
                NSString *urlString = [NSString stringWithFormat:@"%@OPT=1036&msgId=%ld&sign=%@",API_LOGIN_URL_STRING,model.id,sign];
                [[CDHttpHelper defaultCDHttpHelper] get:urlString params:nil success:^(id responseObj) {
                    NSDictionary *dict = [responseObj objectFromJSONData];
                    NSLog(@"%@",dict);
                    NSInteger code = [dict[@"code"] integerValue];
                    if (code == 0) {
                        [_dataArray removeObjectAtIndex:indexPath.row];
                        [_tableView reloadData];
                    }
                } failure:^(NSError *error) {
                    
                } showHUD:NO];
               
            }];
            [alert addAction:action];
            [alert addAction:action2];
            alert.view.backgroundColor = [UIColor colorWithRed:0.0/255 green:0.0/255 blue:0.0/255 alpha:.4];
            [self presentViewController:alert animated:NO completion:nil];
        }
    } failure:^(NSError *error) {
        
    } showHUD:NO];
    
  
   
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
